//添加商品信息
const type = {
  非地方特产:['传统美食','名酒名茶','新鲜水果','腌腊干货','绿色蔬菜','粮油作物','美味湖鲜','特色鲜肉','其它产品'],
  地方特产:['传统美食','名酒名茶','新鲜水果','腌腊干货','绿色蔬菜','粮油作物','美味湖鲜','特色鲜肉','其它产品']
}

const db = wx.cloud.database()
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    p_id:Date.now(),
    fileList: [],
    price:'',
    title:'',
    columns:[
      {
        values: Object.keys(type),
        className: 'column1',
      },
      {
        values: type['非地方特产'],
        className: 'column2',
        defaultIndex: 0,
      }
    ],      
    chooseType:false,
    types:[],
    checked:true,
    cloudUrls:[],
    canIGetStorage:false
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //数据初始化
    init(){
      let fliProduct = wx.getStorageSync('fliProduct')
      if(fliProduct.length != 0){
        let {_id,data,title,price,types,checked} = fliProduct[0]
        this.setData({
          _id,
          fileList:data,
          title,
          price,
          types,
          checked,
          canIGetStorage:true
        })
      }

    },
    //获取展示图
    afterRead(e){
      const { file } = e.detail
      const { fileList = [] } = this.data;
      fileList.push(file);
      this.setData({ fileList });
    },
    // 照片文件删除
    deleteImg(e){
      let index = e.detail.index
      let {fileList} = this.data
      fileList.splice(index,1)
      this.setData({
        fileList,
      })
    },
    //获取产品名称
    getTitle(e){
      let title = e.detail
      this.setData({
        title,
      })
    },

    getPrice(e){
      let price = e.detail
      this.setData({
        price,
      })
    },

    //设置产品类型
    chooseType(){
      let chooseType = this.data.chooseType
      this.setData({
        chooseType:!chooseType,
        types:['非地方特产','传统美食'],
      })
    },
    chooseOver(){
      this.setData({
        chooseType:false
      })
    },
    onChange(e){      
      if(e.detail.value){
        this.setData({
          types:e.detail.value
        })
      }
    },

    //是否上架
    switchonChange(){
      let checked = this.data.checked
      this.setData({
        checked:!checked
      })
    },

    //提交
    submit(){
      this.check()
    },

    check(){
      let {fileList,title,price,types} = this.data
      if(fileList.length < 5){
        wx.showToast({
          title: '图片尚未添加完',
          icon:'error'
        })
      }else if(!title.length){
        wx.showToast({
          title: '产品名称未填写',
          icon:'error'
        })
      }else if(!price.length){
        wx.showToast({
          title: '销售单价未填写',
          icon:'error'
        })
      }else if(!types.length){
        wx.showToast({
          title: '产品类型未选择',
          icon:'error'
        })
      }else{
        if(this.data.canIGetStorage){
          this.updateIndoToCloud()
        }else{
          this.uploadToCloud()
        }

      }

  },

  // 上传图片
  uploadToCloud() {
    wx.cloud.init();
    const { fileList,p_id,title,price,types,checked} = this.data;
    if (!fileList.length) {
      wx.showToast({ title: '请选择图片', icon: 'none' });
    } else {
      const uploadTasks = fileList.map((file, index) => this.uploadFilePromise(`product/${p_id}${index}.png`, file));
      Promise.all(uploadTasks)
        .then(data => {
          wx.showToast({ title: '上传成功', icon: 'none' });
          const newFileList = data.map(item => ({ url: item.fileID }));
          // this.setData({ cloudPath: data, fileList: newFileList });
          this.setData({
            p_id:Date.now(),
            fileList: [],
            price:'',
            title:'',
            chooseType:false,
            types:[],
            checked:true,
            cloudUrls:[]
          })
          this.uploadProductToCloud(newFileList,title,price,types,checked)
        })
        .catch(e => {
          wx.showToast({ title: '上传失败', icon: 'none' });
          console.log(e);
        });
    }
  },

  uploadFilePromise(fileName, chooseResult) {
    return wx.cloud.uploadFile({
      cloudPath: fileName,
      filePath: chooseResult.url
    });
  },

  //上传信息到云端
  uploadProductToCloud(data,title,price,types,checked){
    let phoneNumber = wx.getStorageSync('userInfo').account
    db.collection('products').add({
      data:{
        phoneNumber,
        data,
        title,
        price,
        types,
        checked,
      }
    }).then(()=>{
      this.refresh()
    })
  },

  //更新云端信息
  updateIndoToCloud(){
    let {_id,title,price,types,checked} = this.data
    db.collection('products').doc(_id).update({
      data:{
        title,
        price,
        types,
        checked
      }
    }).then(()=>{
      wx.removeStorageSync('fliProduct')
      wx.navigateTo({
        url: '/pages/store/store',
      })
    }).catch(error=>{
      wx.showToast({
        title: '更新失败',
        icon:'none'
      })
      console.log(error)
    })
  },

  //刷新数据
  refresh(){
    db.collection('products').where({
      phoneNumber,
    }).get().then(res=>{
      wx.setStorageSync('products', res.data)
      this.setData({
        products:res.data
      })
    })
  },
  },
  attached(){
    this.init()
  }

})

